#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
import json
import os
from urllib import request
import MyEncoder


class ImgDownloader(object):
    def __init__(self):
        self.rootPath = "./download/"

    # 数据写入文件
    def collectData(self, data):
        if bool(data) and data['url'] is not None:
            filePath = self.getMd5DataName(data['url'])
            if not os.path.exists(filePath):
                self._mkdirPath(filePath)
                file = open(filePath, "w")
                file.write(json.dumps(data, indent=4))
                file.close()

    def getMd5DataName(self, data):
        return os.path.join(self.rootPath, "datas/info", hashlib.md5(data.encode("utf-8")).hexdigest(), ".json")

    def _mkdirPath(self, filePath):
        dirname = os.path.dirname(filePath)
        if not os.path.exists(dirname):
            os.makedirs(dirname)

    def download(self, data):
        if bool(data) and data['url'] is not None:
            try:
                imgName = str(data['page']) + os.path.splitext(data['src'])[1]
                imgSavePath = self._getImgSavePath(data['types'], data['title'], imgName)
                if not os.path.exists(imgSavePath):
                    self._mkdirPath(imgSavePath)
                    f = open(imgSavePath, 'wb')
                    f.write(request.urlopen(data['src']).read())
                    print(u"==== 下载图片:%s  ==== 下载路径：%s  ====" % (data['title'], data['src']))
                    f.close()
            except Exception as e:
                print(u"=== 下载图片%s(%s)失败 === 错误信息：" % (data['title'], data['src']))
                print(e.args)

    def _getImgSavePath(self, types, title, name):
        tempTypes = ''
        i = 0
        while i < len(types):
            tempTypes = tempTypes + types[i] + "/"
            i = i + 1

        return os.path.join(self.rootPath, "imgs", tempTypes, title, name)
